<template>
  <div>

    <el-card>
      <el-row :gutter="30">
        <el-col :span="5">
          <el-input v-model="adminSearchForm.username" placeholder="用户名" ></el-input>
        </el-col>
        <el-col :span="5">
        <el-select v-model="adminSearchForm.admintype" placeholder="请选择管理员类型">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="success" icon="el-icon-search" @click="handleSearchAdmin" plain>搜索</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="warning" icon="el-icon-refresh-left" @click="resetSearch" plain>重置</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="primary" icon="el-icon-plus" @click="dialogVisible = true" plain>添加</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="danger" icon="el-icon-delete" @click="batchDeleteAdmin" plain>删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-row>
        <el-table
            stripe
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="username"
              label="用户名"
              width="120">
          </el-table-column>
          <el-table-column
              prop="admintype"
              label="管理员类型"
              width="580">
            <template slot-scope="scope">
              <el-tag
                  :type="scope.row.admintype === 0 ? 'primary' : 'danger'"
                  disable-transition>
                {{ scope.row.admintype === 0 ? '普通管理员' : '高级管理员' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="145"
              header-align="center">
            <template slot-scope="scope">
              <div style="display: flex; justify-content: center;">
              <el-button @click="handleEdit(scope.row)" type="primary" plain icon="el-icon-edit" circle size="small"></el-button>
              <el-button type="danger" plain icon="el-icon-delete" circle size="small" @click="deleteAdmin(scope.row)"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="pageData.currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size=pageData.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total">
        </el-pagination>
      </el-row>
    </el-card>

    <el-dialog
        :title="isEditing ? '修改管理员' : '添加管理员'"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose">
      <el-form :model="adminForm" :rules="rules" ref="readerForm">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="adminForm.username" autocomplete="off" :disabled="isEditing"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="adminForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员类型" :label-width="formLabelWidth" prop="admintype">
          <el-select v-model="adminForm.admintype" placeholder="请选择管理员类型">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelDialog">取 消</el-button>
    <el-button type="primary" plain @click="addAdmin">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "AdminViews",
  data() {
    var validateUsername = async (rule, value, callback) => {
      const {data:res} = await this.$axios.get("admin/checkUsername",{params:{username:this.adminForm.username,id:this.adminForm.id}})
      if (res.data==null){
        callback();
      }else if (value===res.data.username && res.data.id !== this.adminForm.id){
        callback(new Error('用户名已存在'));
      }else{
        callback();
      }
    };
    return {
      isEditing: false,
      formLabelWidth: '100px',
      dialogVisible: false,
      options: [{
        value: 0,
        label: '普通管理员'
      }, {
        value: 1,
        label: '高级管理员'
      }],
      adminForm: {
        username: '',
        admintype: '',
        password: '',
        role: '',
        id: ''
      },
      tableData: [],
      pageData:{
        currentPage:1,
        pageSize:5,
        total:0
      },
      adminSearchForm:{
        username: '',
        admintype: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {validator:validateUsername, trigger: 'change'}
        ],
        admintype: [
          { required: true, message: '请选择管理员类型', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ]
      }
    }
  },
  created() {
    this.getAdminList()
  },
  methods:{
    resetForm(){
      this.adminForm = {
        username: '',
        admintype: '',
        password: '',
        role: '',
        id: ''
      };
    },
    cancelDialog() {
      this.resetForm(); // 重置表单数据
      this.$refs.readerForm.clearValidate(); // 清除表单验证状态
      this.dialogVisible = false; // 关闭对话框
      this.isEditing = false; // 重置 isEditing 为 false
    },
    currentChange(val){
      this.pageData.currentPage=val
      this.getAdminList()
    },
    sizeChange(val){
      this.pageData.pageSize=val
      this.getAdminList()
    },
    handleEdit(row) {
      // 将当前行的数据赋值给 adminForm
      this.adminForm = { ...row };
      // 确保 admintype 是数字
      this.adminForm.admintype = Number(this.adminForm.admintype);
      // 设置 isEditing 为 true
      this.isEditing = true;
      // 显示对话框
      this.dialogVisible = true;
    },
    async getAdminList() {
      const params = { ...this.pageData, ...this.adminSearchForm }
      const {data: res} = await this.$axios.get("admin/getAdmin",{params})
      this.tableData = res.data.records
      this.pageData.total=res.data.total
    },
    handleSearchAdmin() {
      this.pageData.currentPage = 1
      this.getAdminList()
    },
    resetSearch() {
      this.adminSearchForm.username = ''
      this.adminSearchForm.admintype = ''
      this.pageData.currentPage = 1;
      this.getAdminList()
    },
    addAdmin() {
      this.$refs.readerForm.validate(async valid => {
        if (valid) {
          try {
            this.adminForm.role = '1';
            let url = "admin/addAdmin";
            if (this.adminForm.id) {
              url = "admin/updateAdmin"; // 如果有 id，则是修改操作
            }
            const { data: res } = await this.$axios.post(url, this.adminForm);
            if (res.success) {
              this.$message.success(this.adminForm.id ? '修改成功' : '添加成功');
              this.dialogVisible = false;
              this.isEditing = false;
              await this.getAdminList();
              this.resetForm();
            } else {
              this.$message.error(res.message || (this.adminForm.id ? '修改失败' : '添加失败'));
            }
          } catch (error) {
            console.error(error);
            this.$message.error(this.adminForm.id ? '修改失败' : '添加失败');
          }
        } else {
          return false;
        }
      });
    },
    deleteAdmin(row){
      this.$confirm('此操作将永久删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data:res}=await this.$axios.get("admin/deleteById",{params:{id:row.id}})
        if (res.success){
          this.$message.success('删除成功')
          await this.getAdminList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    batchDeleteAdmin() {
      const selectedRows = this.$refs.multipleTable.selection;
      if (selectedRows.length === 0) {
        this.$message.warning('请选择要删除的管理员');
        return;
      }
      this.$confirm('此操作将永久删除选中的管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = selectedRows.map(row => row.id);
        const { data: res } = await this.$axios.post("admin/batchDeleteAdmin", ids);
        if (res.success) {
          this.$message.success('删除成功');
          await this.getAdminList();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.resetForm(); // 重置表单数据
            this.$refs.readerForm.clearValidate();
            this.isEditing = false;
            done();
          })
          .catch(_ => {});
    }
  },
}
</script>

<style scoped>
.el-pagination{
  margin-top: 10px;
}
</style>